#!/usr/bin/env bash
export DEBIAN_FRONTEND=noninteractive

# Add MongoDB APT repository
if [ -f "/etc/apt/sources.list.d/10gen.list" ]; then
  echo "MongoDB already added to APT sources"
else
  apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
  echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" > "/etc/apt/sources.list.d/10gen.list"
fi

apt-get update > /dev/null
apt-get -y install autoconf automake bison build-essential curl g++ git-core libc6-dev libreadline6 libreadline6-dev libsqlite3-dev libssl-dev libtool libxml2-dev libxslt-dev libyaml-dev mongodb-10gen ncurses-dev openjdk-7-jdk openjdk-7-jre-headless openssl pkg-config sqlite3 subversion unzip zlib1g zlib1g-dev

# Use chruby to manage Rubies (and ruby-build to build them)
if [ -f "/usr/local/share/chruby/chruby.sh" ]; then
  echo 'chruby already present'
else
  # Download and install chruby
  echo 'chruby not yet installed, installing now...'
  wget -O chruby-0.3.2.tar.gz https://github.com/postmodern/chruby/archive/v0.3.2.tar.gz
  tar -xzvf chruby-0.3.2.tar.gz
  cd chruby-0.3.2/
  make install
  # Add to global profile (enabling chruby for all bash users)
  echo '[ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ] || return' >> /etc/profile.d/chruby.sh
  echo "source /usr/local/share/chruby/chruby.sh" >> /etc/profile.d/chruby.sh
  # Add to global zprofile (enabling chruby for all zsh users)
  echo "source /usr/local/share/chruby/chruby.sh" >> /etc/zsh/zprofile
  # Install ruby-build
  cd
  git clone git://github.com/sstephenson/ruby-build.git
  cd ruby-build
  ./install.sh
  # Use ruby-build to install MRI and JRuby
  ruby-build 1.9.3-p374 /opt/rubies/ruby-1.9.3-p374
  ruby-build jruby-1.7.2 /opt/rubies/jruby-1.7.2
  # Set ruby-1.9 as the global default for bash users
  echo "chruby ruby-1.9" >> /etc/profile.d/chruby.sh
  # Set ruby-1.9 as the global default for zsh users
  echo "chruby ruby-1.9" >> /etc/zsh/zprofile
fi

# Setup the bundle
source /usr/local/share/chruby/chruby.sh 
chruby jruby && gem install bundler && cd /vagrant && bundle
chruby ruby-1.9 && gem install bundler && cd /vagrant && bundle
